using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Input;

namespace S2Engine.Input
{
    /// <summary>
    /// Trata as entradas provinientes do teclado
    /// </summary>
    public sealed class Keyboard
    {
        #region Structs
        /// <summary>
        /// Estado de uma determinada tecla do teclado
        /// </summary>
        struct KeyState
        {
            public bool IsPressed;
            public bool IsTriggered;
            public bool WasPressed;
        };
        #endregion

        #region Attributes
        /// <summary>
        /// Array que armazena o estado de cada tecla do teclado
        /// </summary>
        static KeyState[] keystates = new KeyState[256];
        KeyboardState state;
        #endregion

        #region Constructors
        /// <summary>
        /// Inicia uma instancia do teclado
        /// </summary>
        public Keyboard()
        {

        }
        #endregion

        #region Properties
        public KeyboardState State
        {
            get
            {
                return state;
            }
            set
            {
                state = value;
            }
        }
        #endregion

        #region Methods
        /// <summary>
        /// Retorna true se a tecla estiver pressionada
        /// </summary>
        /// <param name="key">Tecla a ter o estado analisado</param>
        /// <returns></returns>
        public bool IsPressed(Keys key)
        {
            return keystates[(int)key].IsPressed;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool IsTriggered(Keys key)
        {
            return keystates[(int)key].IsTriggered;
        }

        /// <summary>
        /// Atualiza o estado de todas as teclas do teclado
        /// </summary>
        public void Update()
        {
            state = Microsoft.Xna.Framework.Input.Keyboard.GetState();
            for (int i = 0; i < 256; i++)
                keystates[i].IsPressed = false;

            foreach (Keys key in state.GetPressedKeys())
                keystates[(int)key].IsPressed = true;

            for (int i = 0; i < 256; i++)
            {
                if (keystates[i].IsPressed)
                {
                    if (keystates[i].WasPressed)
                        keystates[i].IsTriggered = false;
                    else
                    {
                        keystates[i].WasPressed = true;
                        keystates[i].IsTriggered = true;
                    }
                }
                else
                {
                    keystates[i].WasPressed = false;
                    keystates[i].IsTriggered = false;
                }
            }
        }
        #endregion
    }
}
